package com.sgb.kjwl.view.ui.activity.pick;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;
import com.swgk.core.util.LogUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPickInfoBinding;
import com.sgb.kjwl.di.pick.DaggerPickComponent;
import com.sgb.kjwl.di.pick.PickModule;
import com.sgb.kjwl.view.widget.pick.PickPopWindowView;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.pick.PickInfoListEntity;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.adapter.pick.PickInfoListAdapter;
import com.sgb.kjwl.view.widget.PickAreaPopWindow;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.viewmodel.pick.PickInfoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;


/**
 * 招标信息列表
 */
public class PickInfoActivity extends AppActivity {

    private ActivityPickInfoBinding binding;
    private PickInfoListAdapter pickingAdapter;
    private PickHallBidingPopWindow statusPopWindow;
    private PickHallBidingPopWindow moneyPopWindow;
    private PickAreaPopWindow addrPopWindow;

    @Inject
    PickInfoModel model;

    private List<PickSelectEntity> typeDatas = new ArrayList<>();
    private List<PickSelectEntity> cityDatas = new ArrayList<>();
    private List<PickSelectEntity> provinceDatas = new ArrayList<>();
    //省
    private String areacode;
    private String areaName;
    //地区
    private String citysNo = "";
    //类型
    private String typeNo = "全部";
    private int page = 1;
    //搜索关键字
    private String searchName = "";
    private InputMethodManager im;

    private boolean isLoadMore = false;
    private boolean isChange1;
    private boolean isSearching = false;

    public static void start(Context context) {
        Intent intent = new Intent(context, PickInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPickComponent.builder()
                .appComponent(appComponent)
                .pickModule(new PickModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_pick_info);
        binding.topLayout.ivBack.setOnClickListener(view -> finish());
        binding.tvAddr.setOnClickListener(this);
        binding.topLayout.tvSearch.setOnClickListener(this);
        binding.topLayout.tvSearchDelete.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);

        binding.topLayout.etView.setHint("搜索招标名称");
        binding.topLayout.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.topLayout.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (isSearching) return true;
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.topLayout.etView.getText().toString())) {
                        MToast.showToast(PickInfoActivity.this, "请输入搜索内容");
                        return true;
                    }
                    if (searchName.equals(binding.topLayout.etView.getText().toString())){
                        MToast.showToast(PickInfoActivity.this, "请输入不同的搜索内容");
                        return true;
                    }
                    isSearching = true;
                    searchName = binding.topLayout.etView.getText().toString();
                    if (!TextUtils.isEmpty(searchName)) {
                        isLoadMore = false;
                        page = 1;
                        model.getList(citysNo, typeNo, page, searchName,areacode);
                    }
                }
                return false;
            }
        });

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                LogUtil.v("goodsInfo", "类型=" + typeDatas.get(tab.getPosition()).getProjectscale());
                typeNo = typeDatas.get(tab.getPosition()).getProjectscale();
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        if (pickingAdapter == null) {
            pickingAdapter = new PickInfoListAdapter(getActivity(), null);
        }
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_list_divide));
        binding.recyclerView.addItemDecoration(divider);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(pickingAdapter);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                page = page + 1;
                model.getList(citysNo, typeNo, page, searchName,areacode);
            }
        });

        pickingAdapter.setOnItemClick(new AdapterOnItemClick<PickInfoListEntity>() {
            @Override
            public void onItemClick(PickInfoListEntity tenderListEntity, int position) {
                model.getH5Url(tenderListEntity.getId());
            }
        });

        addrPopWindow = new PickAreaPopWindow(getActivity());
        addrPopWindow.isVisibleBottomLayout(true);
        addrPopWindow.isVisibleNextButton(false);
        addrPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                boolean isCity = (boolean) key3;
                if (isCity) {
                    areacode = (String) key1;
                    citysNo = "";
                } else {
                    citysNo = (String) key1;
                }

                areaName = (String) key2;
                if (!"全国".equals(areaName)) {
                    updateChooseTextStatus(binding.tvAddr,1,areaName);
                    isChange1 = true;
                } else {
                    isChange1 = false;
                    areaName = "地区";
                    updateChooseTextStatus(binding.tvAddr,0,areaName);
                }
                getData();
            }
        });
        addrPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChange1) {
                    updateChooseTextStatus(binding.tvAddr,0,areaName);
                }else{
                    updateChooseTextStatus(binding.tvAddr,1,areaName);
                }
            }
        });
//        addrPopWindow.setiButtonClick(new PickAreaPopWindow.IButtonClick() {
//            @Override
//            public void next(String no) {
//                model.getCityData(no);
//            }
//        });
        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                switch (newState){
                    /*正在拖拽*/
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        /*惯性滑动中*/
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        int position = manager.findLastVisibleItemPosition();
                        if (position > 10) {
                            binding.imgBackTop.setVisibility(View.VISIBLE);
                        } else {
                            binding.imgBackTop.setVisibility(View.GONE);
                        }
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
    }

    @Override
    protected void init() {

        model.getProvinceData();
        model.getFilterTypeData();

        getData();
    }

    private void getData() {
        isLoadMore = false;
        page = 1;
        model.getList(citysNo, typeNo, page, searchName,areacode);
    }

    public void showList(List<PickInfoListEntity> list) {
        isSearching = false;
        binding.recyclerView.refreshComplete();
        if (list == null) {
            binding.emptyView.setVisibility(View.VISIBLE);
            return;
        }
        if(binding.imgBackTop.getVisibility() == View.GONE){
            if(isLoadMore && list.size()>0){
                binding.imgBackTop.setVisibility(View.VISIBLE);
            }else{
                binding.imgBackTop.setVisibility(View.GONE);
            }
        }

        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() > 0) {
                pickingAdapter.addDatas(list);
            } else {
                binding.recyclerView.setLoadingMoreEnabled(false);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            binding.recyclerView.refreshComplete();
            if (list.size() > 8) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                pickingAdapter.setDatas(list);
                binding.recyclerView.setLoadingMoreEnabled(true);
            } else {
                pickingAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (null != im) {
            im.hideSoftInputFromWindow(binding.topLayout.etView.getWindowToken(), 0);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void showUrl(String url) {
        WebViewX5HostActivity.start(getActivity(), url);
    }


    public void setCityDatas(List<PickSelectEntity> datas) {
        cityDatas.clear();
        cityDatas.addAll(datas);
        addrPopWindow.setCityDatas(cityDatas);
    }

    public void setProvinceDatas(List<PickSelectEntity> datas) {
        provinceDatas.clear();
        provinceDatas.addAll(datas);
    }

    public void setTypeDatas(List<PickSelectEntity> datas) {
        typeDatas.clear();
        PickSelectEntity entity = new PickSelectEntity();
        entity.setNo("");
        entity.setProjectscale("全部");
        typeDatas.add(0, entity);
        typeDatas.addAll(datas);
        for (int i = 0; i < typeDatas.size(); i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(typeDatas.get(i).getProjectscale()));
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.tv_addr:
                if (null != provinceDatas && provinceDatas.size() > 0) {
                    if (TextUtils.isEmpty(areaName)) {
                        areaName = "地区";
                    }
                    updateChooseTextStatus(binding.tvAddr, TextUtils.isEmpty(areacode) && TextUtils.isEmpty(citysNo) ? -1 : -2, areaName);
                    addrPopWindow.showPopwindow(binding.roomLayout, 0, 0);
                    addrPopWindow.setBgColor(Color.parseColor("#F5F5F5"));
                    addrPopWindow.setData(provinceDatas);
                }
                break;
            case R.id.tv_search:
                searchName = binding.topLayout.etView.getText().toString();
                if (!TextUtils.isEmpty(searchName)) {
                    isLoadMore = false;
                    page = 1;
                    model.getList(citysNo, typeNo, page, searchName,areacode);
                }
                break;
            case R.id.tv_search_delete:
                isLoadMore = false;
                page = 1;
                binding.topLayout.etView.setText("");
                searchName = "";
                model.getList(citysNo, typeNo, page, searchName,areacode);
                break;
            case R.id.img_back_top:
                binding.imgBackTop.setVisibility(View.GONE);
                binding.recyclerView.getLayoutManager().scrollToPosition(0);
                break;
        }
    }

    /**
     * 更新选项颜色
     */
    private void updateChooseTextStatus(PickPopWindowView pickPopWindowView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            if (!"报名开始时间".equals(name) && !"报名结束时间".equals(name)) {
                if (name.length() > 4) {
                    name = name.substring(0, 4) + "...";
                }
            }

        }
        if (value == -1 || value == -2) {
            binding.popLine.setVisibility(View.VISIBLE);
            pickPopWindowView.setChooseData(R.drawable.member_pop_blue_bg2, R.mipmap.ic_up_arrow_n, R.color.color_333333, true, name);
        } else if (value == 0) {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333, false, name);
        } else {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_new_blue_bg_10, R.mipmap.icon_down_red, R.color.color_main, false, name);
        }
    }
}
